<template>
  <div class="destination-container">
    <a-tabs type="card" @change="callback" v-model="selectedDepartment">
      <a-tab-pane v-for="item in departmentList" :key="item.department_id" :tab="item.department_name"></a-tab-pane>
      <a-space slot="tabBarExtraContent">
        <a-month-picker :allowClear="false" format="YYYY-MM" v-model="year_month" @change="handleChangeMonth" />
      </a-space>
    </a-tabs>
    <vxe-table border resizable keep-source show-overflow="title" ref="xTable" :data="tableData" :height="tableHeight"
      :edit-config="{trigger: 'click', mode: 'cell', showStatus: true, icon: 'vxe-icon-edit'}"
      @edit-closed="editClosedEvent" :row-config="{
      drag: true
    }" :row-drag-config="{
      icon: 'vxe-icon-sort',
       showGuidesStatus: false
    }" @row-dragstart="rowDragstartEvent" @row-dragend="rowDragendEvent">
      <vxe-column width="120" field="person_name" title="人员" fixed="left" drag-sort></vxe-column>
      <vxe-column width="120" field="position" title="职位" fixed="left"></vxe-column>
      <!-- <vxe-column width="120" field="department_name" title="部门"></vxe-column> -->
      <vxe-column v-for="item in tableColumns" :key="item.date" :field="item.date" :title="item.date" :edit-render="{}"
        min-width="160">
        <template #header="{ column }">
          <span :style="['星期六','星期日'].includes(item.weekday) ? { color:'red' } : {}">
            {{item.date}}
          </span>
        </template>
        <template #edit="{ row }">
          <a-input v-model="row[item.date]" type="text" placeholder=""></a-input>
        </template>
      </vxe-column>
    </vxe-table>
  </div>
</template>
<script>
  import {
    apiDestinationGet,
    apiDepartmentList,
    apiDestinationHandle
  } from '@/api/featch'

  import moment from 'moment'

  export default {
    name: 'DestinationEdit',
    data() {
      return {
        selectedDepartment: 4, // 新闻采访部的id
        departmentList: [

          {
            "department_id": 4,
            "department_name": "新闻采访部",
            "sort": 4,
            "is_deleted": 0,
            "person_count": 23
          },
          {
            "department_id": 5,
            "department_name": "报刊部",
            "sort": 5,
            "is_deleted": 0,
            "person_count": 9
          },
          {
            "department_id": 6,
            "department_name": "播音制作部",
            "sort": 6,
            "is_deleted": 0,
            "person_count": 11
          },
          {
            "department_id": 7,
            "department_name": "新媒体部",
            "sort": 7,
            "is_deleted": 0,
            "person_count": 15
          },
          {
            "department_id": 8,
            "department_name": "专题节目部",
            "sort": 8,
            "is_deleted": 0,
            "person_count": 7
          },
          {
            "department_id": 9,
            "department_name": "网络部",
            "sort": 9,
            "is_deleted": 0,
            "person_count": 7
          },
        ],
        year_month: moment(),
        year_month_format: moment().format('YYYY-MM'),
        tableHeight: 0,
        allTableData: [],
        tableData: [],
        tableColumns: []
      }
    },
    mounted() {
      this.initTableHeight()
      window.addEventListener('resize', this.initTableHeight)
      // 获取部门
      // apiDepartmentList()
      //   .then(res => {
      //     if (res.code === 200) {
      //       this.departmentList = res.data
      //     }
      //   })

      this.handleGetInit()
    },
    methods: {
      initTableHeight() {
        const clientHeight = document.documentElement.clientHeight
        this.tableHeight = clientHeight - 40 - 32
      },
      handleGetInit() {
        // 这个月的每一天
        this.tableColumns = this.getDaysInMonth(this.year_month_format)

        // 获取数据
        apiDestinationGet({
          year_month: this.year_month_format,
        }).then(res => {
          this.allTableData = res.data
          this.tableData = this.allTableData.filter(item => {
            return (item.department_id === this.selectedDepartment)
          })
        })
      },
      /**切换tab */
      callback(key) {
        this.selectedDepartment = key
        let tableData = this.allTableData.filter(item => {
          return (item.department_id === this.selectedDepartment)
        })
        if (window.localStorage.getItem(`DestinationEditSortList${key}`)) {
          const sortList = JSON.parse(window.localStorage.getItem(`DestinationEditSortList${key}`))
          tableData = this.sortTableData(tableData, sortList)
          console.log(tableData)
        }
        this.tableData = tableData
      },
      /**这个月的每一天 */
      buildDateColumns(yearMonth) {
        const start = moment(yearMonth, 'YYYY-MM');
        const end = start.clone().endOf('month');
        const days = [];
        let current = start;
        while (current.isSameOrBefore(end)) {
          days.push(current.format('YYYY-MM-DD'));
          current = current.add(1, 'day');
        }
        return days;
      },
      getDaysInMonth(dateStr) {
        const daysArray = [];
        const startOfMonth = moment(dateStr, 'YYYY-MM');
        const endOfMonth = startOfMonth.clone().endOf('month');
        let currentDate = startOfMonth.clone();
        while (currentDate <= endOfMonth) {
          const dayObj = {
            date: currentDate.format('YYYY-MM-DD'),
            weekday: currentDate.format('dddd')
          };
          daysArray.push(dayObj);
          currentDate = currentDate.add(1, 'day');
        }
        return daysArray;
      },
      /** 日期选择器组件 改变回调 */
      handleChangeMonth() {
        this.year_month_format = this.year_month.format('YYYY-MM')
        this.handleGetInit()
      },
      // 编辑表格
      editClosedEvent({
        row,
        column
      }) {
        const $table = this.$refs.xTable
        const field = column.field
        const cellValue = row[field]

        console.log(row, column)
        console.log($table.isUpdateByRow(row, field))
        // 判断单元格值是否被修改
        if ($table.isUpdateByRow(row, field)) {
          apiDestinationHandle({
              person_id: row.person_id,
              specific_date: field,
              destination: cellValue
            })
            .then(res => {
              if (res.code === 200) {
                $table.reloadRow(row, null, field)
              }
            })
        }
      },
      rowDragstartEvent({
        row
      }) {
        // console.log(`拖拽开始 ${row.name}`)
      },
      rowDragendEvent({
        newRow,
        oldRow,
        dragPos
      }) {
        console.log(`拖拽完成，被拖拽行：${oldRow.person_name} 目标行：${newRow.person_name} 目标位置：${dragPos}`)
        const $table = this.$refs.xTable
        if ($table) {
          const tableData = $table.getFullData()
          console.log(tableData)
          // 当前 id
          console.log(this.selectedDepartment)
          // 当前 排序
          const sortList = tableData.map(item => item.person_id)
          console.log(sortList)
          // 存到本地存储
          window.localStorage.setItem(`DestinationEditSortList${this.selectedDepartment}`, JSON.stringify(sortList))
        }
      },
      sortTableData(tableData, sortList) {
        const personIdIndexMap = {};
        sortList.forEach((personId, index) => {
          personIdIndexMap[personId] = index;
        });

        return tableData.sort((a, b) => {
          const indexA = personIdIndexMap[a.person_id];
          const indexB = personIdIndexMap[b.person_id];
          return indexA - indexB;
        });
      }
    },
  };
</script>

<style lang="less" scoped>
  .destination-container {
    height: calc(100vh - 32px);
    overflow-y: hidden;

    /deep/ .ant-tabs-bar {
      margin: 0;
    }

    ::-webkit-scrollbar {
      width: 12px;
      height: 12px;
      /*background-color: #ddd;*/
    }


    /*滑块*/
    ::-webkit-scrollbar-thumb {
      background-color: rgba(83, 166, 255, 0.5);
      border-radius: 8px;
    }

    ::-webkit-scrollbar-thumb:hover {
      background-color: #777;
    }


    /*滑道*/
    ::-webkit-scrollbar-track {
      /* box-shadow: inset 0 0 6px #333; */
      border-radius: 8px;
    }

  }
</style>